<template>
  <view>
    <view class="flex align-center">
      <!-- 打开选择框 -->
      <view @tap.stop="changeStatus" class="color-CCCCCC flex align-center pr-10">

        <view v-if="!isWeek">
          <picker  mode="date" :fields="curUnitType" :value="formatDate" @change="bindDateChange" @cancel="show=false">
			      <view class="flex align-center" :class="{ 'isShow': show }">
              {{ formatDate }}
              <view style="padding-left:6rpx;padding-right:6rpx">
                <u-icon class="arrow" :class="{ 'rotate180': show }" name="arrow-down-fill" size="12">
                </u-icon>
              </view>
            </view>
		      </picker>
        </view>

        <view v-else class="flex align-center">
          <text  :class="{ 'isShow': showWeek }" class="textColor">{{ formatWeekContent }}</text>
          <view :class="{ 'isShow': showWeek }" style="padding-left:6rpx;padding-right:6rpx">
            <u-icon class="arrow" :class="{ 'rotate180': showWeek  }" name="arrow-down-fill" size="12">
            </u-icon>
          </view>
        </view>
      </view>

      <!-- 日期单位选择 -->
      <DropDownSelect :list="dateType" @confirm="confirmDateUnit" label="label" :closeInit="false" />

    </view>

    <!-- 周选择-弹框 -->
    <WeekPicker v-model="showWeek" mode="date" @change="changeWeek" :initDateParams="initDateParams" />
    <!-- 年 月 日 选择-弹框 -->
    <!-- <u-picker mode="time" v-model="show" :params="params" @confirm="confirm" :default-time="defaultTime"></u-picker> -->

  </view>
</template>

<script >
/**
 * @description: 日期选择器，可选择年、月、周、日
 * @param {Object} initData 初始化日期数据
 * @param {Array} disableUnitType 定义不需要的日期单位
 * @param {Boolean} show 展示选择框
 * @param {Boolean} showWeek 展示周单位选择框
 * @param {Boolean} isWeek 是否以周为单位
 * @param {String} unitValue 日期单位值
 * @param {Object} params picker子组件配置项
 * @param {Function} unitChange 日期单位变更回调函数
 * @param {Function} dateChange 日期值变更回调函数
 * @example:
 * <DateTimePicker @unitChange="unitChange" @dateChange="dateChange" :disableUnitType=['day'] />
 */

import DropDownSelect from "./dropDownSelect"
import WeekPicker from "./weekPicker.vue"
import { DIC } from "@/utils/dict"

export default {
  name: 'DateTimePicker',
  components: { DropDownSelect, WeekPicker },
  props:{
    // initData:{
    //   type : Object,
    //   default: ()=> {return {}}
    // },
    disableUnitType:{
      type : Array,
      default: ()=>{
        return []
      }
    }
  },
  created() {
    const nowDate = new Date()
    this.year = nowDate.getFullYear()
    this.month = nowDate.getMonth()+1
    this.day = nowDate.getDate()
  },
  data () {
    return {
      isWeek: false,
      show: false,
      showWeek: false,
      // params: {
      //   year: true,
      //   month: false,
      //   day: false,
      //   hour: false,
      //   minute: false,
      //   second: false
      // },
      year: '',
      month: '',
      week: '',
      day: '',
      unitValue: 0,
      initDateParams : {}
    }
  },
  computed: {
    dateType () {
      return DIC.dateType.filter(el=>{
        return !this.disableUnitType.includes(el.type)
      })
    },
    //更改选择器的 日期选择方式
    curUnitType () {
      return this.dateType.find(el => el.value === this.unitValue)?.type
    },
    //周-格式 数据展示
    formatWeekContent () {
      let result = `${this.year}-${this.week}周`
      return result || '选择日期'
    },
    formatDate(){
      let dateStr = this.year
      if(this.unitValue === DIC.dateType[1].value){
        dateStr += `-${ (this.month+'').padStart( 2 ,'0') }`
      }else if(this.unitValue === DIC.dateType[3].value){
        dateStr += `-${ (this.month+'').padStart(2,'0') }-${(this.day+'').padStart(2,'0') }`
      }
      return dateStr
    }
    //根据year 和 month 限制 以周为单位的时候选择的范围
    // weekMinDate () {
    //   const now = new Date()
    //   if (this.year && this.month) {
    //     return `${this.year}-${this.month}`
    //   } else if (this.year) {
    //     return `${this.year}`
    //   } else if (this.month) {
    //     return `${now.getFullYear()}-${this.month}`
    //   } else {
    //     return `${now.getFullYear()}-${now.getMonth()+1}`
    //   }
    // }
  },
  methods: {
    bindDateChange: function(e) {
      this.show = false
      const dateList = e.target.value.split("-")
      if(dateList[0]){
        this.year = parseInt(dateList[0])
      }
      if(dateList[1]){
        this.month = parseInt(dateList[1])
      }
      if(dateList[2]){
        this.day = parseInt(dateList[2])
      }
      this.dateChange()
    },
    changeStatus () {
      //isWeek 分开展示选择器
      if (this.isWeek) {
        //展示周组件
        this.showWeek = true
      } else {
        this.show = true
      }
    },
    //确认当前选择的日期单位
    confirmDateUnit (unitValue) {
      if (unitValue !== this.unitValue) {
        //如果是周选择，需展示另一个组件 ,由 isWeek 判断
        if (unitValue === DIC.dateType[2].value) {
          this.isWeek = true
          if(!this.week){
            const dateStart = new Date(this.year, 0, 1)
            let dateEnd = new Date()
            this.initDateParams = {
              month : dateEnd.getMonth(),
              day : dateEnd.getDate()
            }
            const dateEndYear = dateEnd.getFullYear()
            //如果已选择的年份不是当年
            if(this.year != dateEndYear){
              dateEnd.setFullYear(this.year)
              this.initDateParams.year = this.year
            }else{
              this.initDateParams.year = dateEndYear
            }
            const oneDayTime = 24 * 60 * 60 * 1000;
            const dataEndNumber = Math.round((dateEnd.valueOf() - dateStart.valueOf()) / oneDayTime)
            this.week = Math.ceil((dataEndNumber + dateStart.getDay()) / 7)
          }
        } else {
          this.isWeek = false
          const now = new Date()
          if(!this.month){
            this.month = now.getMonth()+1
          }
          if(!this.day){
            this.day = now.getDate()
          }
        }
        this.unitValue = unitValue
        this.$emit('unitChange', unitValue)
        this.dateChange()
      }
    },
    //确认周的选择
    changeWeek (weekRange) {
      this.week = weekRange.yearWeek
      //如果 year 有传 就更新
      if(weekRange.year){
        this.year = weekRange.year
      }
      this.dateChange()
    },
    //日期 变化通知
    dateChange () {
      this.$emit('dateChange', {
        year: this.year,
        month:this.month,
        week:this.week,
        day:this.day
      })
    }
  },
}

</script>

<style lang="scss" scoped>
.textColor{
  transition: all 0.3s;
}
.isShow {
  color: #2D8CF0 !important;

  * {
    color: #2D8CF0 !important;
  }
}

.rotate180 {
  transform: rotate(180deg) scale(.7) !important;
}

.arrow {
  transform: rotate(0) scale(.7);
  transition: all 0.2s;
}
</style>
